#!/usr/bin/env python
# coding: utf-8

import json
import web
import requests
import time
import re
import os
import pymysql.cursors

# # Connect to the database
# connection = pymysql.connect(host='localhost',
#                              user='root',
#                              password='root',
#                              db='wxbot',
#                              charset='utf8mb4',
#                              cursorclass=pymysql.cursors.DictCursor)
#
# try:
#     with connection.cursor() as cursor:
#         # Create a new record
#         sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
#         cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
#
#     # connection is not autocommit by default. So you must commit to save
#     # your changes.
#     connection.commit()
#
#     with connection.cursor() as cursor:
#         # Read a single record
#         sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
#         cursor.execute(sql, ('webmaster@python.org',))
#         result = cursor.fetchone()
#         print(result)
# finally:
#     connection.close()

#
#
# db = web.database(dbn="sqlite", db=os.path.join(os.path.dirname(os.getcwd()), 'data', 'weixin.db'))
# keywords = db.query("SELECT keywords.id, keywords.coin_name FROM keywords")
# for x in keywords:
#     print(x)

mysql_db = web.database(dbn="mysql", user='root', pw='root', db='wxbot', host='127.0.0.1')

'''
coin 数据插入
'''
# data = [
#     {"name": "Bitcoin", "symbol": "BTC", "rank": 1, "slug": "bitcoin", "tokens": ["Bitcoin", "bitcoin", "BTC"],
#      "id": 1}
# ]
# for x in data:
#     x['tokens'] = json.dumps(x['tokens'])
#     x['coin_name'] = x['name']
#     x.pop('name')
# print(data)
# res = mysql_db.multiple_insert("biben_coin_types", values=data)
# print(res)
# for x in data:
#     x['tokens'] = json.dumps(x['tokens'])
#     print(x)
#     res = mysql_db.insert("biben_coin_types", x)
#     print(res)


'''
调用keywords
'''
str = 'BTC'
config = {
    'reply_templates': u"""
        coinmarketcap网%s价格:￥%10.6f
        24h涨幅:%5.2f %%
        市值排名：%d
        对应CNY汇率：￥%10.6f
        市值：￥%d
        更多: http://www.biben.com/
        【%s】
        """
}
# keywords = mysql_db.query("SELECT coin_name from biben_coin_types")
keywords = mysql_db.select("biben_coin_types")
print (keywords)
for x in keywords:
    if x['symbol'] == str:
        print(x)
        url = "https://api.coinmarketcap.com/v1/ticker/%s/%s" % (x['coin_name'], '?convert=CNY')
        # import pdb
        # pdb.set_trace()
        res = requests.get(url)
        print(res.json()[0])
        print type(res.json()[0]['market_cap_cny'])
        print(config['reply_templates'] % (res.json()[0]['symbol'], float(res.json()[0]['price_cny']), float(res.json()[0]['percent_change_24h']),
                                                       int(res.json()[0]['rank']), float(res.json()[0]['price_cny']), int(res.json()[0]['market_cap_cny']),
                                                       time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(res.json()[0]['last_updated'])))))
        '''
        JSON返回值 = [{u'24h_volume_cny': u'52414118208.0', u'market_cap_usd': u'156672769176', u'price_usd': u'9218.16', u'last_updated': u'1524556471', u'name': u'Bitcoin', u'24h_volume_usd': u'8301780000.0', u'percent_change_7d': u'14.2', u'symbo
l': u'BTC', u'max_supply': u'21000000.0', u'rank': u'1', u'percent_change_1h': u'-0.21', u'total_supply': u'16996100.0', u'price_btc': u'1.0', u'price_cny': u'58199.774976', u'available_supply': u'16996100.0', u'percent_change_2
4h': u'3.42', u'id': u'bitcoin', u'market_cap_cny': u'989169195470'}]
        @param 参数说明
        id  查询接口名称
        name    币名称
        symbol  币简称||标志
        rank    排行
        price_usd   1btc 对应 美元 汇率
        price_btc   1btc
        24h_volume_usd  24小时美元交易量
        market_cap_usd  美元市值
        available_supply    可用供给量
        total_supply    总供给量
        max_supply  最大供给量
        percent_change_1h   1小时变化量
        percent_change_24h  24小时变化量
        percent_change_7d   7天变化量
        last_updated    更新时间
        price_cny   1btc 对应 RMB 汇率价格
        24h_volume_cny  交易量（24小时）
        market_cap_cny  RMB市值
        '''

#!/usr/bin/env python
# coding: utf-8
#####插件说明#####
# 自动根据币种调用查询接口进行指定模板回复
import json
import web
import re
import os
import requests
import time


def run(WXBOT, msg, plugin_name):
    try:
        WXBOT.bot_conf[plugin_name]
    except:
        WXBOT.bot_conf[plugin_name] = {
            'switch': True,  # 自动发消息功能开关
            'default_currency': "CNY",  # 默认货币
            'reply_templates': u"""coinmarketcap网\n币种：%s\n价格：￥%s\n24h涨幅：%s %%\n市值排名：%d\nCNY汇率：￥%s\n市值：￥%s\n更多：http://www.biben.com/\n【%s】"""
        }  # 消息模板
        return
    # 连接数据库
    mysql_db = web.database(dbn="mysql", user='root', pw='root', db='wxbot', host='127.0.0.1')

    # 联系人消息 群消息自动回复
    if WXBOT.bot_conf[plugin_name]['switch'] == True and (msg['msg_type_id'] == 3 and msg['content']['type'] == 0):
        keywords = mysql_db.select("biben_coin_types")
        for x in keywords:
            if x['symbol'] == msg['content']['data'].upper():
                # 找到消息,拼接消息并群内通知
                res = requests.get("https://api.coinmarketcap.com/v1/ticker/%s/%s" % (
                    x['coin_name'], '?convert=' + WXBOT.bot_conf[plugin_name]['default_currency']))

                send_message = WXBOT.bot_conf[plugin_name]['reply_templates'] % (
                    res.json()[0]['symbol'], res.json()[0]['price_cny'],
                    res.json()[0]['percent_change_24h'],
                    int(res.json()[0]['rank']), res.json()[0]['price_cny'], res.json()[0]['market_cap_cny'],
                    time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(res.json()[0]['last_updated']))))

                WXBOT.send_msg_by_uid(send_message, msg['user']['id'])
                # 打印输出发送日志
                print u'[INFO] s测试消息发送成功，%s---->%s\n%s' % (
                    msg['user']['name'], msg['content']['user']['name'], msg['content']['data'])

    # 联系人消息 自动回复
    if WXBOT.bot_conf[plugin_name]['switch'] == True and (msg['msg_type_id'] == 4 and msg['content']['type'] == 0):
            print '12'
            print msg['content']['type']
            print msg['msg_type_id']
            pass

